<template>
  <div class="basic-content">
    <el-row>
      <el-col :span="20">
        <div class="title">
          <el-tag type="info">基2表只能审核结果：</el-tag>
          <el-tag>单价核算正常</el-tag>
          <el-tag>同比环比变化幅度正常</el-tag>
          <!-- <el-tag type="danger">
              注：上报后发现数据错误，①上级部门没有审核可以点击撤回按钮调整，②如已审核点击纠正按钮调整，③如已汇总则无法再调整
            </el-tag> -->
        </div>
      </el-col>
    </el-row>
    <el-form :model="listform" size="small">
      <el-row>
        <el-col :span="24">
          <el-table
            ref="excelTable"
            :data="listform.list"
            style="width: 100%; margin-bottom: 20px"
            border
            height="600px"
          >
            <el-table-column label="指标名称" prop="name" align="center">
              <template slot-scope="scope">
                <div class="extext-area" v-if="scope.row.numType === 3">
                  <span>{{ scope.row.name }}</span>
                  <span>{{ scope.row.extext }}</span>
                </div>
                <div v-else class="name-area">
                  <span
                    :class="
                      scope.row.isChildren === 1
                        ? 'children1'
                        : scope.row.isChildren === 2
                        ? 'children2'
                        : scope.row.isChildren === 3
                        ? 'children3'
                        : scope.row.isChildren === 4
                        ? 'children4'
                        : scope.row.isChildren === 5
                        ? 'children5'
                        : ''
                    "
                  >
                    {{
                      scope.row.isChildren === 3
                        ? "其中：" + scope.row.name
                        : scope.row.name
                    }}
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="计量单位"
              prop="unit"
              align="center"
              width="160"
            >
            </el-table-column>
            <el-table-column
              v-if="$route.query.disabled == 1"
              label="数量"
              prop="value"
              width="300"
              align="center"
            ></el-table-column>
            <el-table-column
              v-else
              label="数量"
              prop="value"
              width="300"
              align="center"
            >
              <template slot-scope="scope">
                <el-form-item class="cellCenter">
                  <span v-if="scope.row.notInput">-</span>
                  <el-input
                    size="small"
                    :type="scope.row.numType === 3 ? 'textarea' : 'number'"
                    :rows="scope.row.numType === 3 ? 5 : null"
                    v-model="scope.row.value"
                    @input="handleInput"
                    @blur="handleCalculate"
                    :disabled="disabledFlage"
                    v-else
                  >
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="上期数据"
              prop="lastValue"
              align="center"
              width="160"
            >
            </el-table-column>
            <el-table-column
              label="环比(%)"
              prop="loopRatio"
              align="center"
              width="160"
            >
            </el-table-column>
            <el-table-column
              label="去年同期数据"
              prop="lastYearvalue"
              align="center"
              width="160"
            >
            </el-table-column>
            <el-table-column
              label="同比(%)"
              prop="togetherRatio"
              align="center"
              width="160"
            >
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { getInfo } from "@/api/login";
import tableConst from "@/views/work/accounts/newadd/components/tableConst4.js";
import {
  deepClone,
  replaceInteger,
  replaceDigit,
  recentlyYearMonth,
  dealElectricity2,
} from "@/utils/index";
import {
  postLedger,
  putLedger,
  getLedgerDetail,
  getLedgerlastmonth,
  getLedgerlastyear,
  reportLedger,
  collectLedgerself,
} from "@/api/standingbook/newstandingbook.js";
export default {
  props: {},
  components: {},
  data() {
    return {
      deptLevel: null,
      listform: {
        principalUnit: "",
        principalStatistics: "",
        formPepole: "",
        phone: "",
        date: "",
        list: deepClone(tableConst.tableData),
      },
      listRules: {
        // value: [{ required: true, message: "不能为空", trigger: "blur" }],
      },
      disabledFlage: false,
      lastMonthData: {},
      lastYearData: {},
      idChildrenMsg: false, // 是否为子部门信息
      isCorrect: false,
    };
  },
  created() {
    this.getDeptLevel();
  },
  mounted() {
    this.judgedisabledFlage();
  },
  methods: {
    judgedisabledFlage() {
      let query = this.$route.query;
      // this.deptLevel = this.$store.state.user.deptLevel;
      this.lastMonthData = {};
      this.lastYearData = {};
      // 查看详情
      if (query.id && String(query.id).length > 0) {
        if (query.disabled == "1") {
          this.disabledFlage = true;
        }
        this.getData(query);
      } else {
        this.disabledFlage = false;
        this.requestLedgerlastmonth(query);
        this.requestLedgerlastyear(query);
      }
      // 查看子部门详情
      if (query.childrenDeptid && String(query.childrenDeptid).length > 0) {
        this.idChildrenMsg = true;
      } else {
        this.idChildrenMsg = false;
      }

      // 纠正
      if (query.correct == "1") {
        this.isCorrect = true;
      } else {
        this.isCorrect = false;
      }
    },
    async getDeptLevel() {
      const res = await getInfo();
      this.deptLevel = res.user.deptLevel;
    },
    getData(query) {
      getLedgerDetail(query.id)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let newData = res?.data ?? {};
          if (Object.keys(newData).length > 0) {
            for (let key in newData) {
              this.listform.list.map((item) => {
                if (item.fields == key) {
                  if (typeof newData[key] == "number") {
                    let result = 0;
                    if (item.numType == 0) {
                      result = dealElectricity2(newData[key], 1, 2);
                      // result = String(newData[key]);
                    } else {
                      result = String(newData[key]);
                    }
                    item.value = result;
                  } else {
                    if (item.fields == "specialSituationDescription") {
                      item.value = newData[key];
                    }
                  }
                }
              });
            }
          }
          this.requestLedgerlastmonth(query);
          this.requestLedgerlastyear(query);
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    requestLedgerlastmonth(query) {
      let deptId;
      if (this.idChildrenMsg) {
        deptId = this.$route.query.childrenDeptid;
      } else {
        deptId = this.$store.state.user.deptId;
      }
      let year = query.year;
      let month = query.month;
      let params = {
        deptId: deptId,
        year: year,
        month: month,
      };
      getLedgerlastmonth(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let data = res?.data ?? {};
          this.lastMonthData = { ...data };
          this.dealLastData(this.lastMonthData, 1);
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    requestLedgerlastyear(query) {
      let deptId;
      if (this.idChildrenMsg) {
        deptId = this.$route.query.childrenDeptid;
      } else {
        deptId = this.$store.state.user.deptId;
      }
      let year = query.year;
      let month = query.month;
      let params = {
        deptId: deptId,
        year: year,
        month: month,
      };
      getLedgerlastyear(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let data = res?.data ?? {};
          this.lastYearData = { ...data };
          this.dealLastData(this.lastYearData, 2);
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    dealLastData(data, calculateType) {
      // calculateType 1：上个月  2：上一年
      if (Object.keys(data).length > 0) {
        for (let key in data) {
          this.listform.list.map((item) => {
            if (item.fields == key) {
              if (typeof data[key] == "number") {
                // 上期数据
                let lastNum = data[key];
                //  除了特殊情况说明 可再生能源应用 外
                let lastratio = "0";
                if (
                  item.fields != "specialSituationDescription" &&
                  item.fields != "kzsnyyy"
                ) {
                  // 上期比率
                  if (Number(item.value) == 0) {
                    lastratio = "0";
                  } else {
                    if (lastNum == 0) {
                      lastratio = "0";
                    } else {
                      let num = Number(item.value) / lastNum;
                      lastratio = replaceDigit(num * 100, 2);
                    }
                  }
                }
                if (calculateType == 1) {
                  item.lastValue = dealElectricity2(lastNum, 1, 2);
                  item.loopRatio = lastratio;
                }
                if (calculateType == 2) {
                  item.lastYearvalue = dealElectricity2(lastNum, 1, 2);
                  item.togetherRatio = lastratio;
                }
              }
            }
          });
        }
      }
    },
    handleCalculate() {
      this.dealLastData(this.lastMonthData, 1);
      this.dealLastData(this.lastYearData, 2);
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      //row:对象形式，保存了当前行的数据
      //column：对象形式，保存了当前列的参数
      //rowIndex:当前行的行号
      //column：当前列的列号
      if (rowIndex === 23) {
        if (columnIndex === 0) {
          return [1, 2];
        } else if (columnIndex === 1) {
          return [0, 0];
        } else if (columnIndex === 2) {
          return [1, 5];
        }
      }
    },
    // 表格输入框输入限制 正整数 ,两位小数
    handleInput(val) {
      this.listform.list.map((item) => {
        if (
          item.value != null &&
          item.value != "" &&
          item.value != "0" &&
          item.value != "-"
        ) {
          if (item.numType == 0) {
            if (Number(item.value) > 999999999) {
              item.value = "0";
              this.$message({
                message: "数值不能大于10亿",
                type: "warning",
              });
            }
            item.value = replaceDigit(Number(item.value), 2).toString();
          } else if (item.numType == 1) {
            if (Number(item.value) > 999999999) {
              item.value = "0";
              this.$message({
                message: "数值不能大于10亿",
                type: "warning",
              });
            }
            item.value = replaceInteger(Number(item.value)).toString();
          }
        }
        // if (item.children && item.children.length > 0) {
        //   item.children.map((tig) => {
        //     if (
        //       tig.value != null &&
        //       tig.value != "" &&
        //       item.value != "0" &&
        //       item.value != "-"
        //     ) {
        //       if (item.numType == 0) {
        //         item.value = replaceDigit(Number(item.value), 2).toString();
        //       } else if (item.numType == 1) {
        //         item.value = replaceInteger(Number(item.value)).toString();
        //       }
        //     }
        //   });
        // }
      });
    },
    handlerSubmit() {
      let deptId = this.$store.state.user.deptId;
      let query = this.$route.query;
      let year = query.year;
      let month = query.month;
      let params = {};
      params.deptId = deptId;
      params.year = year;
      params.month = month;
      this.listform.list.map((item) => {
        let key = item.fields;
        if (!item.notInput) {
          params[key] = item.value;
        }
      });
      this.$modal
        .confirm("确认保存" + year + month + "的台账吗？")
        .then(() => {
          this.requestSave(params, 1);
        })
        .catch(() => {
          this.$message({
            message: "取消保存",
          });
        });
    },
    // 保存并上报或者保存并汇总按钮
    parentTelltodo() {
      let deptId = this.$store.state.user.deptId;
      let query = this.$route.query;
      let year = query.year;
      let month = query.month;
      let params = {};
      params.deptId = deptId;
      params.year = year;
      params.month = month;
      this.listform.list.map((item) => {
        let key = item.fields;
        if (!item.notInput) {
          params[key] = item.value;
        }
      });
      let moName = "";
      if (this.deptLevel == 0) {
        moName = "上报";
      } else if (this.deptLevel == 1 || this.deptLevel == 2) {
        moName = "汇总";
      }
      this.$modal
        .confirm("确认保存并" + moName + year + month + "的台账吗？")
        .then(() => {
          this.requestSave(params, 2);
        })
        .catch(() => {
          this.$message({
            message: "取消保存并" + moName,
          });
        });
    },
    requestSave(params, falge) {
      let query = this.$route.query;
      if (query.id && String(query.id).length > 0) {
        // 修改
        params.id = query.id;
        this.edit(params, falge);
      } else {
        // 新增
        this.add(params, falge);
      }
    },
    add(params, falge) {
      postLedger(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let id = res?.data;
          if (falge == 1) {
            this.$message.success("保存成功");
            setTimeout(() => {
              this.$router.push({ path: "/work/standbook/newadd" });
            }, 200);
          } else {
            this.collectOrrequest(id);
          }
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    edit(params, falge) {
      putLedger(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          if (falge == 1) {
            this.$message.success("修改成功");
            setTimeout(() => {
              this.$router.push({ path: "/work/standbook/newadd" });
            }, 200);
          } else {
            this.collectOrrequest(this.$route.query.id);
          }
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    // 上报or汇总
    collectOrrequest(id) {
      let params = {
        ledgerIds: [],
      };
      params.ledgerIds.push(id);
      if (this.deptLevel == 0) {
        // "上报";
        this.requestReport(params);
      } else if (this.deptLevel == 1 || this.deptLevel == 2) {
        // "汇总";
        this.requestCollect(params);
      }
    },
    //上报请求
    requestReport(params) {
      reportLedger(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("已保存并上报!");
          setTimeout(() => {
            this.$router.push({ path: "/work/standbook/newadd" });
          }, 200);
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    // 汇总请求
    requestCollect(params) {
      collectLedgerself(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("已保存并汇总!");
          setTimeout(() => {
            this.$router.push({ path: "/work/standbook/newadd" });
          }, 200);
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.basic-content {
  width: 100%;

  ::v-deep .title {
    margin-top: 20px;
    .el-tag {
      margin-right: 10px !important;
      margin-bottom: 20px;
    }
  }
}
.row-inline {
  height: 68px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.table-border-line {
  border-top: 4px solid #d2d2d8;
  border-bottom: 4px solid #d2d2d8;
  // padding: 20px 0 10px 0;
  // padding-top: 10px;
  margin-bottom: 10px;
}
.cellCenter {
  margin-top: 0px;
  margin-bottom: 0;
  .el-input {
    width: 200px;
  }
}
.extext-area {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  span {
    &:nth-child(2) {
      margin-top: 20px;
    }
  }
}
.name-area {
  display: flex;
  align-items: flex-start;
  margin-left: 5px;
  .children1 {
    margin-left: 20px;
  }
  .children2 {
    margin-left: 40px;
  }
  .children3 {
    margin-left: 40px;
  }
  .children4 {
    margin-left: 100px;
  }
  .children5 {
    margin-left: 85px;
  }
}
</style>
